package com.tegtech.api.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.tegtech.api.system.domain.LoginBody;
import com.tegtech.api.system.service.ISysMenuService;
import com.tegtech.common.domain.Result;
import com.tegtech.module.auth.domain.SysMenu;
import com.tegtech.module.auth.domain.SysUser;
import com.tegtech.starter.security.SecurityUtils;
import com.tegtech.starter.security.service.SysLoginService;
import com.tegtech.starter.security.service.SysPermissionService;

/**
 * 登录验证
 * 
 * @author Jun
 */
@RestController
public class SysLoginController {
	
	@Autowired
	private SysLoginService loginService;

	@Autowired
	private ISysMenuService menuService;

	@Autowired
	private SysPermissionService permissionService;

	/**
	 * 登录方法
	 * 
	 * @param loginBody 登录信息
	 * @return 结果
	 */
	@PostMapping("/login")
	public Result login(@RequestBody LoginBody loginBody) {
		// 生成令牌
		String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid());
		return Result.ok().data(token);
	}

	/**
	 * 获取用户信息
	 * 
	 * @return 用户信息
	 */
	@GetMapping("getInfo")
	public Result getInfo() {
		SysUser user = SecurityUtils.getLoginUser().getUser();
		// 角色集合
		Set<String> roles = permissionService.getRolePermission(user);
		// 权限集合
		Set<String> permissions = permissionService.getMenuPermission(user);
		Map<String, Object> data = new HashMap<>(3);
		data.put("user", user);
		data.put("roles", roles);
		data.put("permissions", permissions);
		return Result.ok().data(data);
	}

	/**
	 * 获取路由信息
	 * 
	 * @return 路由信息
	 */
	@GetMapping("getRouters")
	public Result getRouters() {
		List<SysMenu> menus = menuService.selectMenuTreeByUserId(SecurityUtils.getCurrentUserId());
		return Result.ok().data(menuService.buildMenus(menus));
	}
}
